package com.hsjk.szwj.module.pay.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hsjk.szwj.framework.common.constant.CommonConstant;
import com.hsjk.szwj.framework.common.exception.ServiceException;
import com.hsjk.szwj.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.hsjk.szwj.module.pay.dal.dataobject.system.MchPayPassageDO;
import com.hsjk.szwj.module.pay.dal.dataobject.system.PayInterfaceDefineDO;
import com.hsjk.szwj.module.pay.dal.mysql.IMchPayPassageMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chenjiawei
 * @desc
 * @Date 2023/08/22 00:45
 **/
@Service
public class MchPayPassageService extends ServiceImpl<IMchPayPassageMapper, MchPayPassageDO> {
    @Resource
    private PayInterfaceDefineService payInterfaceDefineService;

    public List<JSONObject> selectAvailablePayInterfaceList(String wayCode, Long appId,
                                                            Integer infoType, Integer mchType) {
        Map params = new HashMap(4);
        params.put("wayCode", wayCode);
        params.put("appId", appId);
        params.put("infoType", infoType);
        params.put("mchType", mchType);
        List<JSONObject> list = baseMapper.selectAvailablePayInterfaceList(params);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        // 添加通道状态
        for (JSONObject object : list) {
            MchPayPassageDO payPassage = baseMapper.selectOne(
                    new LambdaQueryWrapper<MchPayPassageDO>()
                            .eq(MchPayPassageDO::getAppId, appId)
                            .eq(MchPayPassageDO::getWayCode, wayCode)
                            .eq(MchPayPassageDO::getIfId, object.getStr("ifId"))
            );
            if (payPassage != null) {
                object.putIfAbsent("passageId", payPassage.getId());
                if (payPassage.getRate() != null) {
                    object.putIfAbsent("rate",
                            payPassage.getRate().multiply(new BigDecimal("100")));
                }
                object.putIfAbsent("state", payPassage.getState());
            }
            if (object.getBigDecimal("ifRate") != null) {
                object.putIfAbsent("ifRate",
                        object.getBigDecimal("ifRate").multiply(new BigDecimal("100")));
            }
        }
        return list;
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdateBatchSelf(List<MchPayPassageDO> mchPayPassageList, Long mchId) {
        for (MchPayPassageDO payPassage : mchPayPassageList) {
            if (CommonConstant.NO.equals(payPassage.getState())
                    && payPassage.getId() == null) {
                continue;
            }
            // 商户系统配置通道，添加商户号参数
            if (ObjectUtil.isNotNull(mchId)) {
                payPassage.setMchId(mchId);
            }
            if (payPassage.getRate() != null) {
                payPassage.setRate(payPassage.getRate()
                        .divide(new BigDecimal("100"), 6, BigDecimal.ROUND_HALF_UP));
            }
            if (!saveOrUpdate(payPassage)) {
                throw new ServiceException(GlobalErrorCodeConstants.BAD_REQUEST.getCode(),
                        "操作失败");
            }
        }
    }


    /**
     * 根据应用ID 和 支付方式， 查询出商户可用的支付接口
     **/
    public MchPayPassageDO findMchPayPassage(Long mchId, Long appId, String wayCode) {

        List<MchPayPassageDO> list = list(new LambdaQueryWrapper<MchPayPassageDO>()
                .eq(MchPayPassageDO::getMchId, mchId)
                .eq(MchPayPassageDO::getAppId, appId)
                .eq(MchPayPassageDO::getState, CommonConstant.YES)
                .eq(MchPayPassageDO::getWayCode, wayCode)
        );

        if (list.isEmpty()) {
            return null;
        } else { // 返回一个可用通道

            HashMap<Long, MchPayPassageDO> mchPayPassageMap = new HashMap<>();

            for (MchPayPassageDO mchPayPassage : list) {
                mchPayPassageMap.put(mchPayPassage.getIfId(), mchPayPassage);
            }
            // 查询ifCode所有接口
            PayInterfaceDefineDO interfaceDefine = payInterfaceDefineService
                    .getOne(new LambdaQueryWrapper<PayInterfaceDefineDO>()
                                    .select(PayInterfaceDefineDO::getId,
                                            PayInterfaceDefineDO::getState)
                                    .eq(PayInterfaceDefineDO::getState, CommonConstant.YES)
                                    .in(PayInterfaceDefineDO::getId, mchPayPassageMap.keySet()),
                            false);

            if (interfaceDefine != null) {
                return mchPayPassageMap.get(interfaceDefine.getId());
            }
        }
        return null;
    }

}
